<template>
    
    <!-- 页面头部：标题+筛选 -->
    <div class="page-header">
      <el-row :gutter="20" align="middle">
        <el-col>
          <h2>测试报告中心</h2>
        </el-col>
        <el-col :align="`right`">
          <!-- 报告时间筛选 -->
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="small"
            style="width: 300px; margin-right: 10px"
            @change="getReportList"
          />
          <!-- 报告状态筛选 -->
          <el-select
            v-model="reportStatus"
            placeholder="报告状态"
            size="small"
            style="width: 150px"
            @change="getReportList"
          >
            <el-option label="全部" value="" />
            <el-option label="执行成功" value="success" />
            <el-option label="有失败用例" value="fail" />
          </el-select>
        </el-col>
      </el-row>
    </div>

    <!-- 报告列表 -->
    <el-card shadow="hover" style="margin-top: 15px">
      <el-table
        v-loading="loading"
        :data="reportList"
        border
        stripe
        size="small"
        style="width: 100%"
      >
        <el-table-column prop="id" label="报告ID" width="80" align="center" />
        <el-table-column prop="report_name" label="报告名称" align="center" />
        <el-table-column label="执行时间" align="center" width="180">
          <template #default="scope">{{ formatTime(scope.row.create_time) }}</template>
        </el-table-column>
        <el-table-column label="用例总数" align="center" width="100">
          <template #default="scope">{{ scope.row.total_cases }}</template>
        </el-table-column>
        <el-table-column label="成功数" align="center" width="100">
          <template #default="scope">
            <span class="text-success">{{ scope.row.success_cases }}</span>
          </template>
        </el-table-column>
        <el-table-column label="失败数" align="center" width="100">
          <template #default="scope">
            <span class="text-danger">{{ scope.row.fail_cases }}</span>
          </template>
        </el-table-column>
        <el-table-column label="通过率" align="center" width="100">
          <template #default="scope">
            <el-progress
              :percentage="scope.row.pass_rate"
              :stroke-width="6"
              :format="(percentage) => `${percentage}%`"
              style="width: 80px"
            />
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.pass_rate === 100 ? 'success' : 'danger'">
              {{ scope.row.pass_rate === 100 ? '执行成功' : '有失败用例' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template #default="scope">
            <el-button type="text" size="small" @click="previewReport(scope.row.id)">
              <el-icon><Eye /></el-icon> 预览
            </el-button>
            <el-button type="text" size="small" @click="downloadReport(scope.row.id)">
              <el-icon><Download /></el-icon> 下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[10, 20, 50]"
        :page-size="limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 15px; text-align: right"
      />
    </el-card>

    <!-- 报告预览弹窗 -->
    <el-dialog
      v-model="previewVisible"
      title="测试报告详情"
      width="90%"
      :fullscreen="isFullscreen"
      @close="handleClosePreview"
    >
      <!-- 全屏切换按钮 -->
      <template #header>
        <div class="dialog-header">
          <span>测试报告详情</span>
          <el-button
            type="text"
            size="small"
            @click="isFullscreen = !isFullscreen"
          >
            <el-icon>{{ isFullscreen ? <FullscreenExit /> : <Fullscreen /> }}</el-icon>
          </el-button>
        </div>
      </template>

      <div class="report-preview-header">
        <div class="report-title">{{ currentReport.report_name || '测试报告' }}</div>
        <div class="report-meta">
          <span>生成时间：{{ formatTime(currentReport.create_time) }}</span>
          <span style="margin-left: 20px">报告ID：{{ currentReport.id }}</span>
        </div>
      </div>

      <!-- 报告统计概览 -->
      <div class="report-stats">
        <el-row :gutter="20" style="margin-top: 20px">
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-label">用例总数</div>
              <div class="stat-value">{{ currentReport.total_cases || 0 }}</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card success">
              <div class="stat-label">成功用例</div>
              <div class="stat-value">{{ currentReport.success_cases || 0 }}</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card danger">
              <div class="stat-label">失败用例</div>
              <div class="stat-value">{{ currentReport.fail_cases || 0 }}</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-label">通过率</div>
              <div class="stat-value">{{ currentReport.pass_rate || 0 }}%</div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 失败用例详情（若有） -->
      <div class="fail-cases-section" v-if="currentReport.fail_cases > 0">
        <h3 style="margin-top: 20px">失败用例详情</h3>
        <el-table
          :data="currentReport.fail_cases_detail || []"
          border
          size="small"
          style="width: 100%; margin-top: 10px"
        >
          <el-table-column prop="case_id" label="用例ID" width="80" align="center" />
          <el-table-column prop="case_name" label="用例名称" align="center" />
          <el-table-column prop="error_msg" label="失败原因" align="center" min-width="300">
            <template #default="scope">
              <div class="error-msg">{{ scope.row.error_msg || '无详细信息' }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="120">
            <template #default="scope">
              <el-button type="text" size="small" @click="gotoCase(scope.row.case_id)">
                查看用例
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 无失败用例提示 -->
      <div v-else-if="currentReport.total_cases > 0" style="text-align: center; padding: 30px">
        <el-empty description="本次执行所有用例均通过" />
      </div>

      <!-- 报告为空提示 -->
      <div v-else style="text-align: center; padding: 30px">
        <el-empty description="暂无报告详情数据" />
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClosePreview">关闭</el-button>
          <el-button type="primary" @click="downloadReport(currentReport.id)">
            <el-icon><Download /></el-icon> 下载报告
          </el-button>
        </div>
      </template>
    </el-dialog>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElProgress, ElTag, ElEmpty, ElIcon } from 'element-plus'
import { Eye, Download, Fullscreen, FullscreenExit } from '@element-plus/icons-vue'
import request from '@/api/request'

// 报告列表数据
const reportList = ref([])
const total = ref(0)
const page = ref(1)
const limit = ref(10)
const loading = ref(false)

// 筛选条件
const dateRange = ref([]) // 日期范围 [开始日期, 结束日期]
const reportStatus = ref('') // 报告状态：success/fail

// 预览弹窗相关
const previewVisible = ref(false)
const currentReport = ref({}) // 当前预览的报告详情
const isFullscreen = ref(false) // 是否全屏预览

const router = useRouter()

// 页面挂载时加载报告列表
onMounted(() => {
  getReportList()
})

// 1. 获取报告列表（对接Django接口）
const getReportList = async () => {
  loading.value = true
  try {
    // 处理日期参数（转为YYYY-MM-DD格式）
    const startDate = dateRange.value[0] ? formatDate(dateRange.value[0]) : ''
    const endDate = dateRange.value[1] ? formatDate(dateRange.value[1]) : ''

    const res = await request.get('/api/reports/list/', {
      params: {
        page: page.value, // 修复：明确传递响应式变量值
        limit: limit.value,
        start_date: startDate,
        end_date: endDate,
        status: reportStatus.value
      }
    })
    reportList.value = res.data?.list || [] // 修复：兼容后端返回结构可能的缺失
    total.value = res.data?.total || 0
  } catch (error) {
    ElMessage.error('获取报告列表失败：' + (error.response?.data?.msg || error.message))
  } finally {
    loading.value = false
  }
}

// 2. 预览报告详情
const previewReport = async (reportId) => {
  if (!reportId) {
    ElMessage.warning('报告ID无效')
    return
  }
  try {
    const res = await request.get(`/api/reports/${reportId}/`)
    currentReport.value = res.data || {} // 修复：确保数据为空时不报错
    previewVisible.value = true
  } catch (error) {
    ElMessage.error('获取报告详情失败：' + (error.response?.data?.msg || error.message))
  }
}

// 3. 下载报告（对接Django下载接口）
const downloadReport = async (reportId) => {
  if (!reportId) {
    ElMessage.warning('报告ID无效')
    return
  }
  try {
    // 后端返回文件流，前端触发下载
    const res = await request.get(`/api/reports/${reportId}/download/`, {
      responseType: 'blob' // 关键：指定响应类型为二进制流
    })
    // 从响应头获取文件名（如果后端设置了的话）
    const contentDisposition = res.headers['content-disposition']
    let fileName = `测试报告_${reportId}.html`
    if (contentDisposition) {
      const match = contentDisposition.match(/filename="(.+)"/)
      if (match && match[1]) fileName = decodeURIComponent(match[1])
    }
    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([res.data])) // 修复：正确获取blob数据
    const a = document.createElement('a')
    a.href = url
    a.download = fileName
    document.body.appendChild(a)
    a.click()
    // 清理
    window.URL.revokeObjectURL(url)
    document.body.removeChild(a)
    ElMessage.success('报告下载成功')
  } catch (error) {
    ElMessage.error('下载报告失败：' + (error.response?.data?.msg || error.message))
  }
}

// 4. 跳转到失败用例详情页
const gotoCase = (caseId) => {
  if (!caseId) {
    ElMessage.warning('用例ID无效')
    return
  }
  previewVisible.value = false
  router.push({ path: '/case-manage', query: { caseId } }) // 修复：正确传递查询参数
}

// 5. 关闭预览弹窗
const handleClosePreview = () => {
  previewVisible.value = false
  currentReport.value = {} // 清空当前报告数据
}

// 分页相关方法
const handleSizeChange = (val) => {
  limit.value = val
  page.value = 1 // 重置到第一页
  getReportList()
}
const handleCurrentChange = (val) => {
  page.value = val
  getReportList()
}

// 工具函数：格式化时间（YYYY-MM-DD HH:MM:SS）
const formatTime = (timeStr) => {
  if (!timeStr) return '无数据'
  try {
    const date = new Date(timeStr)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    }).replace(/\//g, '-')
  } catch (error) {
    return timeStr // 格式化失败时返回原始字符串
  }
}

// 工具函数：格式化日期（YYYY-MM-DD）
const formatDate = (date) => {
  if (!date) return ''
  try {
    const d = new Date(date)
    return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`
  } catch (error) {
    return ''
  }
}
</script>

<style scoped lang="scss">
.report-center-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 15px;
  h2 {
    margin: 0;
    font-size: 18px;
    color: #333;
  }
}

// 表格文字样式
.text-success {
  color: #67c23a;
}
.text-danger {
  color: #f56c6c;
}

// 弹窗头部样式
.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

// 报告预览弹窗样式
.report-preview-header {
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
  .report-title {
    font-size: 20px;
    font-weight: bold;
    color: #333;
    margin-bottom: 10px;
  }
  .report-meta {
    color: #666;
    font-size: 14px;
  }
}

// 统计卡片样式
.report-stats {
  .stat-card {
    text-align: center;
    padding: 15px 0;
    .stat-label {
      font-size: 14px;
      color: #666;
      margin-bottom: 5px;
    }
    .stat-value {
      font-size: 24px;
      font-weight: bold;
      color: #333;
    }
    &.success .stat-value {
      color: #67c23a;
    }
    &.danger .stat-value {
      color: #f56c6c;
    }
  }
}

// 失败用例详情样式
.fail-cases-section {
  .error-msg {
    color: #f56c6c;
    white-space: pre-wrap; // 保留换行符
    word-break: break-all; // 长文本自动换行
  }
}

// 弹窗底部按钮样式
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>